using B.S.Medical.Api.Write.Application.Command.Pay;
using B.S.Medical.Domain.Medical;
using B.S.Medical.Domain.Payment;
using B.S.Medical.ErrorCode;
using B.S.Medical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using B.S.Medical.Domain.Medical;

namespace B.S.Medical.Api.Write.Application.Handler.Pay
{
    /// <summary>
    /// 修改支付订单状态处理器
    /// </summary>
    public class UpdatePaymentStatusHandler : IRequestHandler<UpdatePaymentStatusCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<PaymentRecordModel> _paymentRepository;
        private readonly IBaseRepository<PatientBalance> _patientBalanceRepository;
        private readonly ILogger<UpdatePaymentStatusHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        public UpdatePaymentStatusHandler(
            IBaseRepository<PaymentRecordModel> paymentRepository,
            IBaseRepository<PatientBalance> patientBalanceRepository,
            ILogger<UpdatePaymentStatusHandler> logger)
        {
            _paymentRepository = paymentRepository;
            _patientBalanceRepository = patientBalanceRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理修改支付订单状态命令
        /// </summary>
        public async Task<ApiResult<bool>> Handle(UpdatePaymentStatusCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation($"开始更新订单状态: OrderNo={request.OrderNo}, PayStatus={request.PayStatus}");

                // 查询订单
                var paymentRecord = _paymentRepository.GetAll()
                    .Where(p => p.OrderNo == request.OrderNo && !p.IsDeleted)
                    .FirstOrDefault();

                if (paymentRecord == null)
                {
                    _logger.LogWarning($"未找到订单: {request.OrderNo}");
                    return new ApiResult<bool>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "未找到订单",
                        Data = false
                    };
                }

                // 更新订单状态
                paymentRecord.IsPaid = request.IsPaid;
                paymentRecord.PayStatus = request.PayStatus;
                if (!string.IsNullOrEmpty(request.TradeNo))
                {
                    paymentRecord.PayTradeNo = request.TradeNo;
                }
                if (request.PayTime.HasValue)
                {
                    paymentRecord.PayTime = request.PayTime.Value;
                }
                else if (request.IsPaid && !paymentRecord.PayTime.HasValue)
                {
                    paymentRecord.PayTime = DateTime.Now;
                }
                if (!string.IsNullOrEmpty(request.PayType))
                {
                    paymentRecord.PayType = request.PayType;
                }
                if (!string.IsNullOrEmpty(request.PayChannel))
                {
                    paymentRecord.PayChannel = request.PayChannel;
                }
                if (!string.IsNullOrEmpty(request.NotifyRaw))
                {
                    paymentRecord.NotifyRaw = request.NotifyRaw;
                }
                paymentRecord.UpdateTime = DateTime.Now;

                // 余额处理逻辑
                var patientBalance = _patientBalanceRepository.GetAll()
                    .Where(b => b.PatientId == paymentRecord.PatientId && !b.IsDeleted)
                    .FirstOrDefault();
                
                // 支付成功处理
                if (request.PayStatus == "TRADE_SUCCESS" || request.PayStatus == "已支付")
                {
                    // 检查是否为余额充值订单
                    bool isRecharge = paymentRecord.ItemName == "余额充值";
                    _logger.LogInformation($"订单 {request.OrderNo} 支付成功, 类型: {(isRecharge ? "余额充值" : "普通支付")}");
                    
                    if (patientBalance != null)
                    {
                        if (isRecharge)
                        {
                            // 余额充值，增加余额
                            patientBalance.Balance += paymentRecord.Amount;
                            patientBalance.Remark = $"充值 {paymentRecord.Amount} 元";
                            _logger.LogInformation($"余额充值成功: 患者ID={paymentRecord.PatientId}, 金额={paymentRecord.Amount}, 当前余额={patientBalance.Balance}");
                        }
                        else
                        {
                            // 普通支付，扣减余额
                            if (paymentRecord.PayAmount > 0)
                            {
                                patientBalance.Balance -= paymentRecord.PayAmount;
                                _logger.LogInformation($"支付扣款: 患者ID={paymentRecord.PatientId}, 金额={paymentRecord.PayAmount}, 当前余额={patientBalance.Balance}");
                            }
                        }
                        
                        patientBalance.UpdateTime = DateTime.Now;
                        patientBalance.LastUpdatedTime = DateTime.Now;
                        await _patientBalanceRepository.UpdateAsync(patientBalance);
                    }
                    // 如果是充值但没有余额记录，创建新的余额记录
                    else if (isRecharge)
                    {
                        var newBalance = new PatientBalance
                        {
                            PatientId = paymentRecord.PatientId,
                            Balance = paymentRecord.Amount,
                            UpdateTime = DateTime.Now,
                            LastUpdatedTime = DateTime.Now,
                            Remark = $"首次充值 {paymentRecord.Amount} 元"
                        };
                        
                        await _patientBalanceRepository.CreateAsync(newBalance);
                        _logger.LogInformation($"为患者ID={paymentRecord.PatientId}创建余额记录，首次充值金额={paymentRecord.Amount}");
                    }
                }
                // 退款处理
                else if (request.PayStatus == "TRADE_REFUND" || request.PayStatus == "已退款")
                {
                    //if (patientBalance != null && paymentRecord.RefundAmount.HasValue && paymentRecord.RefundAmount.Value > 0)
                    //{
                        // 只有普通支付的退款才增加余额，充值的退款不处理余额
                        if (paymentRecord.ItemName != "余额充值")
                        {
                            patientBalance.Balance += paymentRecord.RefundAmount.Value;
                            patientBalance.UpdateTime = DateTime.Now;
                            patientBalance.LastUpdatedTime = DateTime.Now;
                            patientBalance.Remark = $"退款 {paymentRecord.RefundAmount.Value} 元";
                            
                            await _patientBalanceRepository.UpdateAsync(patientBalance);
                            _logger.LogInformation($"退款到余额: 患者ID={paymentRecord.PatientId}, 金额={paymentRecord.RefundAmount.Value}, 当前余额={patientBalance.Balance}");
                        }
                    //}
                }

                // 保存订单
                await _paymentRepository.UpdateAsync(paymentRecord);

                _logger.LogInformation($"订单状态和余额更新成功: OrderNo={request.OrderNo}, PayStatus={request.PayStatus}, IsPaid={request.IsPaid}");

                return new ApiResult<bool>
                {
                    Code = ApiEnum.Success,
                    Msg = "订单状态更新成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新订单状态失败: OrderNo={request.OrderNo}, Error={ex.Message}");
                return new ApiResult<bool>
                {
                    Code = ApiEnum.Error,
                    Msg = $"更新订单状态失败: {ex.Message}",
                    Data = false
                };
            }
        }
    }
} 